package com.song.tools.songtest.trigger.sysuser;

import com.song.tools.core.enums.DeletedEnum;
import com.song.tools.core.util.UserUtil;
import com.song.tools.songtest.beans.bo.SysRoleUserBo;
import com.song.tools.songtest.beans.request.SysRoleUserGrantRolesRequest;
import com.song.tools.songtest.beans.response.SysRoleUserGrantRolesResponse;
import com.song.tools.songtest.constants.TriggerTypeEnum;
import com.song.tools.songtest.manager.SysRoleUserManager;
import com.song.tools.trigger.AbstractTriggerTemplate;
import com.song.tools.trigger.TriggerContext;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 给用户设置角色-触发器
 *
 * @author song tools
 * @since 2024-07-19
 */
@Slf4j
@Component
public class GrantRoleForUserTrigger extends AbstractTriggerTemplate<SysRoleUserGrantRolesRequest, SysRoleUserGrantRolesResponse> {
    @Resource
    private SysRoleUserManager sysRoleUserManager;

    public GrantRoleForUserTrigger() {
        super(TriggerTypeEnum.GRANT_ROLE_FOR_USER);
    }

    /**
     * 触发
     *
     * @param triggerContext 触发上下文
     * @return 触发结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysRoleUserGrantRolesResponse trigger(TriggerContext<SysRoleUserGrantRolesRequest> triggerContext) {
        SysRoleUserGrantRolesRequest request = triggerContext.getTriggerRequest();
        Long userId = request.getUserId();
        List<Long> roleIds = request.getRoleIds();
        // 删除用户角色关系
        sysRoleUserManager.deleteByUserId(userId);

        // 批量插入用户角色关系
        List<SysRoleUserBo> sysRoleUserBoList = new ArrayList<>();
        for (Long roleId : roleIds) {
            SysRoleUserBo sysRoleUserBo = new SysRoleUserBo();
            sysRoleUserBo.setUserId(userId);
            sysRoleUserBo.setRoleId(roleId);
            sysRoleUserBo.setRemark(request.getRemark());

            sysRoleUserBo.setCreateUserId(UserUtil.get().id());
            sysRoleUserBo.setCreateUsername(UserUtil.get().username());
            sysRoleUserBo.setCreateTime(LocalDateTime.now());
            sysRoleUserBo.setUpdateUserId(UserUtil.get().id());
            sysRoleUserBo.setUpdateUsername(UserUtil.get().username());
            sysRoleUserBo.setUpdateTime(LocalDateTime.now());
            sysRoleUserBo.setDeleted(DeletedEnum.NOT_DELETED.getCode());
            sysRoleUserBoList.add(sysRoleUserBo);
        }

        sysRoleUserManager.saveBatch(sysRoleUserBoList);
        // 返回响应
        SysRoleUserGrantRolesResponse response = new SysRoleUserGrantRolesResponse();
        response.setRoleIds(roleIds);
        response.setUserId(userId);
        return response;
    }
}
